<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(  
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('send','view','list'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','admin','delete','create','update'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{  
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('admin','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('admin','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{  
	  	$this->redirect(array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User']; 
		
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionList()
	{   
		 
		$filter =(!isset($_REQUEST['filter'])?0:$_REQUEST['filter']); 

	 	$dataProvider=CompanyUser::model()->search($filter);   

	 	$commpany =Company::model()->find('id=:id',array(':id'=>Yii::app()->user->id));

	 	$smscount = $commpany->point;

		$filterarray=array(
			array('id'=>'0','name'=>'全部'),
			array('id'=>'1','name'=>'最近一周到店会员'),
			array('id'=>'2','name'=>'最近一月到店会员'),
			array('id'=>'3','name'=>'最近一月未到店会员'),
			array('id'=>'4','name'=>'最近三月未到店会员'),
		);

		$this->render('list',array(
			'filterarray'=>$filterarray,'dataProvider'=>$dataProvider,'filter'=>$filter,'smscount'=>$smscount,
		));
	}

	/**
	 * 用户发送短信
	 */
	public function actionSend()
	{ 
		 
		if(empty($_POST['sendSelect'])){
			 
		    $selectids=$_POST['selectids'];
			$callback = $_POST['callback'];
			if(empty($_POST['sendmessage'])){ 
				unset($_POST);
				return $this->render('send',array(
					'model'=>array(
						'selectids'=>$selectids,
						'callback'=>$callback,
						'errormessage'=>'请输入发送内容',
					),
				)); 
			}
			$commpany=Company::model()->find("id=:id",array(":id"=>Yii::app()->user->id));  
			//发送的内容 
            $content=$_POST['sendmessage']." 【".$commpany->title."】"; 
            //内容拆分成几条短信
            $lines=ceil($this->utf8_strlen($content)/50); 
 
            $selectidarray=explode(',',$selectids);
            $result = count($selectidarray); 
      		 //判断账户里是不是够发本次短信的费用
			if(!(Company::model()->isSend(Yii::app()->user->id,$result*$lines))){
				return $this->render('send',array(
					'model'=>array(
						'selectids'=>$selectids,
						'callback'=>$callback,
						'errormessage'=>'您的账户余额不能支撑本次的短信发送,请充值',
						'sendmessage'=>$_POST['sendmessage'],
					),
				)); 	
			}

		    $criteria= new CDbCriteria;  
       	    $criteria->addInCondition('id', $selectidarray);  
       	    $models=User::model()->findAll($criteria);//Words换成你的模型   
       	    
			 $senlen=0;//定义发送成功的条数 
			//给用户发送信息
			foreach ($models as $key => $value) { 
				$senlen=$this->sendSMSAndSave($value['id'],$value['mobile'],$content) ? $senlen+1 : $senlen;
			} 
			//扣除用户发送的费用
		     Company::model()->deductions(Yii::app()->user->id,$senlen*$lines);
		    //转向发送的来源
		     return $this->redirect($callback);
		}
		//判断是不是多选界面进来的
		if(!empty($_POST['sendSelect'])){
			 $selectidarray=explode(',',$_POST['selectid']);
			 $criteria= new CDbCriteria;  
	       	 $criteria->addInCondition('id', $selectidarray);  
	       	 $models=User::model()->findAll($criteria);//Words换成你的模型  
	       	 $mobiles=array();
	       	 foreach ($models as $key => $value) {
	       	 	array_push($mobiles,preg_replace("/(1\d{1,3})\d\d(\d{0,2})/", "\$1****\$3", $value->mobile));
	       	 }
       	}else{ 
       		return $this->redirect($callback);
       	}
		$this->render('send',array(
			'model'=>array(
				'mobiles'=>implode(',', $mobiles),
				'selectids'=>empty($_POST['selectid'])?"":$_POST['selectid'],
				'callback'=>Yii::app()->request->urlReferrer,
			),
		));
	}

		/**
		 * 得到字符串长度
		 *
		 * @package default
		 * @author 
		 **/  
 		private function utf8_strlen($string = null) 
 		{
			// 将字符串分解为单元
			preg_match_all("/./us", $string, $match);
			// 返回单元个数
			return count($match[0]);
		}

		/**
		 * 发送短信，并保存到发送日志中
		 *
		 * @package default
		 * @author 
		 **/ 
		private function sendSMSAndSave($id,$mobile,$content){
			// $model=$this->loadModel($id);
			 //发送短消息，并将记录到消息信息中 
			 $res = User::model()->sendSMS($mobile,$content); 
			 // $res ='success';
			 Yii::app()->format->datetimeFormat='Y-m-d H:i:s';
			  if($res =='success'){
			  	//添加发送日志
			  	 $sendsmslog = new Sendsmslog();
			   	 $sendsmslog->userid=$id;
			   	 $sendsmslog->companyid=Yii::app()->user->id;
			   	 $sendsmslog->mobile=$mobile;
			   	 $sendsmslog->sended=1;
			   	 $sendsmslog->content=$_POST['sendmessage'];
			   	 $sendsmslog->createtime=Yii::app()->format->formatDateTime(time());
			   	 $sendsmslog->save();
			   	//更新企业用户的最后发送时间
			   	 $commpanyUser= CompanyUser::model()->find('userid=:userid and companyid=:companyid',array(':userid'=>$id,':companyid'=>Yii::app()->user->id));
			   	 if(!empty($commpanyUser)){
			   	 	$commpanyUser->lastsendtime = Yii::app()->format->formatDateTime(time());
			   	 	$commpanyUser->save();
			   	 }

			   	return true;
			  } 
		 return false;
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
